package uploadFile;


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFileWithFileUploader extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(factory);
		try {
			List<FileItem> fileItems = sfu.parseRequest(request);
			for(int i=0;i<fileItems.size();i++){
				FileItem item= fileItems.get(i);
				if(item.isFormField()){
					String fieldName=item.getFieldName();
					String fieldValue=item.getString();
					System.out.println(fieldName+","+fieldValue);
				}else{
					String type = item.getContentType();
					System.out.println("type:"+type);
					if(type.toLowerCase().endsWith("jpeg")){
						String fileName=item.getName();
						fileName=fileName.substring(fileName.lastIndexOf("/")+1);
						String path=getServletContext().getRealPath("uploadedFile");
						System.out.println(path);
						File file = new File(path+"/"+fileName);
						System.out.println(file.getAbsolutePath());
						item.write(file);
						out.print("file uploaded");
					}else{
						request.setAttribute("notJpg", "not jpg");
						request.getRequestDispatcher("uploadFile/uploadFile.jsp").forward(request, response);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
